package com.damage.business_dept.web;

import com.damage.business_dept.service.ISupplierService;
import com.damage.common.entity.Supplier;
import com.damage.common.exception.UniqueException;
import com.damage.common.object.BaseResp;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@ResponseBody
@RequestMapping("/supplier")
public class SupplierController {

    @Autowired
    private ISupplierService supplierService;

    @PostMapping("/new")
    public BaseResp newSupplier(Supplier supplier){
        try {
            Integer result = supplierService.newSupplier(supplier);
            if (result > 0){
                return BaseResp.ok();
            }else {
                return BaseResp.error();
            }
        } catch (UniqueException e) {
            return BaseResp.error(e.getMessage());
        }
    }

    @GetMapping("/findAll")
    public BaseResp findAll(Integer pageNum){
        PageInfo<Supplier> result = supplierService.findAll(pageNum);
        if (result != null){
            return BaseResp.ok(result);
        }else{
            return BaseResp.error();
        }
    }

    @GetMapping("/findSupplier")
    public BaseResp findSupplier(String name,Integer pageNum){
        PageInfo<Supplier> result = supplierService.findSupplier(pageNum,name);
        if (result != null){
            return BaseResp.ok(result);
        }else{
            return BaseResp.error();
        }
    }

    @GetMapping("/findById")
    public BaseResp findById(Integer id){
        Supplier supplier = supplierService.findById(id);
        if (supplier != null){
            return BaseResp.ok(supplier);
        }else{
            return BaseResp.error();
        }
    }

    @PostMapping("/update")
    public BaseResp updateSupplier(Supplier supplier){
        Integer result = supplierService.update(supplier);
        if (result > 0){
            return BaseResp.ok();
        }else{
            return BaseResp.error();
        }
    }

    @PostMapping("/delete")
    public BaseResp deleteSupplier(Integer id){
        Integer result = supplierService.deleteById(id);
        if (result > 0){
            return BaseResp.ok();
        }else{
            return BaseResp.error();
        }
    }
}
